﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace HeathCareSystem
{
    public class DonThuocDAO
    {
        DataProvider dp = new DataProvider();

        public int LayMaTaiKhoanCuoi()
        {
            DataTable dt = new DataTable();
            string strSQL = string.Format("SELECT TOP 1 MaDonThuoc FROM DONTHUOC ORDER BY MaDonThuoc DESC");
            dt = dp.ExecuteQuery(strSQL);
            return int.Parse(dt.Rows[0][0].ToString());
        }

        public DonThuocDTO LayThongTinDonThuoc(int maChiTietBenhAn, string ngayLap)
        {
            DonThuocDTO donThuocDTO = new DonThuocDTO();
            string strSQL = string.Format("Select * from DonThuoc " +
                                          " where MaChiTietBenhAn = {0} AND NgayLap = CONVERT(DATETIME, '{1}', 102)",
                                            maChiTietBenhAn, ngayLap);
            DataTable dt = dp.ExecuteQuery(strSQL);
            foreach (DataRow dr in dt.Rows)
            {                
                donThuocDTO.maChiTietBenhAn = int.Parse(dr["MaChiTietBenhAn"].ToString());
                donThuocDTO.maDonThuoc = int.Parse(dr["MaDonThuoc"].ToString());
                donThuocDTO.ngayLap = DateTime.Parse(dr["Ngaylap"].ToString());
                donThuocDTO.ghiChu = dr["GhiChu"].ToString();                
            }
            return donThuocDTO;
        }

        public bool ThemDonThuocMoi(DonThuocDTO dt)
        {
            string strSQL = string.Format("INSERT INTO DonThuoc (GhiChu, MaChiTietBenhAn, NgayLap) "+
                                          " VALUES (N'{0}', {1}, '{2}')",
                                            dt.ghiChu, dt.maChiTietBenhAn, dt.ngayLap);
            return dp.ExecuteNonQuery(strSQL);
        }

        public bool KiemTraToaThuoc(int maChiTietBenhAn, string ngayLap)
        {
            string strSQL = string.Format("Select * from DonThuoc "+
                                          " WHERE maChiTietBenhAn = {0} and NgayLap = CONVERT(DATETIME, '{1}', 102)", 
                                          maChiTietBenhAn, ngayLap);
            DataTable dt = dp.ExecuteQuery(strSQL);
            if (dt.Rows.Count > 0)
                return true;
            return false;
        }
    }
}